<template>
  <div
      :id="from+'AllMap'"
      v-bind:style="{'opacity': isShow?'1':'0','width':isShow?'100%':'0px','height':isShow?'100%':'0px'}">
  </div>
</template>

<script>
  import Log from '../../mod/log.js';
  import strings from '../../assets/strings';
  import cordova from '../../js/cordova-app';

  import ToastUtils from '../../mod/utils.toast';
  import WeChatUtils from '../../js/wechat';
  import StringUtils from '../../js/mod.string';

  const name = "activity-clock-map>";
  const log = new Log(name);

  export default {
    props: ['from', 'longitude', 'latitude', 'range', 'isShow', 'isMark',
      'isChangeMark'],
    components: {},
    data() {
      return {
        name: name,

        icon_wechat: './static/images/map_green.png',
        icon_dingding: './static/images/map_blue.png',
        curLongitude: null,
        curLatitude: null,
        // 百度定位对象
        positionObj: null,
        distance: null,

        isClock: false,// 位置是否在范围内
      };
    },
    computed: {},
    watch: {
      /*isClock() {
       let _this = this;
       _this.$emit('changeIsClockStatus', _this.isClock);
       },*/
    },
    methods: {
      onCreated() {
        let _this = this;
      },
      onMounted() {
        let _this = this;
        _this.$f7ready((f7) => {
          if ((_this.longitude && _this.latitude) || _this.isChangeMark == true) {
            _this.getCurPosition()
                .then((r) => {
                  var longitude = r.lng;
                  var latitude = r.lat;
                  _this.setBaiduPosition(longitude, latitude);
                  _this.getisClock();
                })
                .catch(err => {
                  _this.setBaiduPosition();
                });
            //_this.setBaiduPosition();
          }

//          if (_this.isMark) {
//            setTimeout(() => {
//              if (_this.longitude && _this.latitude) {
//                _this.setMarkAtMap(_this.longitude, _this.latitude);
//              }
//            }, 500);
//          }
        });
      },
      // 位置是否在范围内
      getisClock: function () {
        let _this = this;
        let is_clock = false;
        if (_this.longitude && _this.latitude && _this.curLongitude
            && _this.curLatitude) {
          let point1 = new BMap.Point(_this.curLongitude,
              _this.curLatitude);
          let point2 = new BMap.Point(_this.longitude, _this.latitude);
          let distance = _this.positionObj.getDistance(point1, point2);
          if (distance != 0) {
            distance = distance.toFixed(0);
          }
          //alert('距离米数：' + distance);
          _this.distance = parseInt(distance);
          is_clock = (_this.range && _this.distance && (_this.range >= _this.distance));
        }
        _this.isClock = is_clock;
        _this.$emit('changeIsClockStatus', _this.isClock);
      },

      setBaiduPosition(_longitude, _latitude) {
        let _this = this;
        // 百度地图API功能
        let map = new BMap.Map(_this.from + "AllMap");
        _this.positionObj = map;
        //36.6905979383,117.0643349229 洪兴大厦
        let point = new BMap.Point((_longitude || 117.0643349229), (_latitude || 36.6905979383));
        map.centerAndZoom(point, 14);
        _this.positionObj.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

        _this.setMyselfPositionIcon(point);

        if (_this.isChangeMark) {
          let showInfo = function (e) {
            let mark_longitude = e.point.lng ? e.point.lng : 0;
            let mark_latitude = e.point.lat ? e.point.lat : 0;
            _this.setMarkAtMap(mark_longitude, mark_latitude);
            _this.$emit('changeMark', {
              longitude: mark_longitude,
              latitude: mark_latitude,
            });
          };
          _this.positionObj.addEventListener("click", showInfo);
        }
        if (_this.isMark) {
          if (_this.longitude && _this.latitude) {
            _this.setMarkAtMap(_this.longitude, _this.latitude);
          }
        }

        // 判断手机浏览器是否支持定位
        // let geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function (r) {
        //   if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        // let latitude = r.point.lat;
        // let longitude = r.point.lng;
        // let address = '';
        // let mk = new BMap.Marker(r.point);
        // map.addOverlay(mk);
        // map.panTo(r.point);
        // alert('您的位置：' + r.point.lng + ',' + r.point.lat);
        //   } else {
        //     let status = this.getStatus();
        //     // alert('failed' + this.getStatus());
        //   }
        // }, {enableHighAccuracy: true});
      },
      setMyselfPositionIcon(_point) {
        let _this = this;
        let iconUrl = (_this.$f7.data.from == 'wechat') ? _this.icon_wechat
            : _this.icon_dingding;
        let myPositionIcon = new BMap.Icon(iconUrl, new BMap.Size(24, 24));
        myPositionIcon.setImageSize(new BMap.Size(24, 24));
        //let markMy = new BMap.Marker(_point, {icon: myPositionIcon});
        let markMy = new BMap.Marker(_point);
        _this.positionObj.addOverlay(markMy);
      },
      getCurPosition() {
        let _this = this;

        // 腾讯地图坐标转换为百度地图坐标
        let tacentToBaiduMap = function (lng, lat) {
          let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
          let x = lng;
          let y = lat;
          let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
          let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
          let lngs = z * Math.cos(theta) + 0.0065;
          let lats = z * Math.sin(theta) + 0.006;
          return {
            lng: lngs,
            lat: lats
          }
        };

        return new Promise((resolve, reject) => {
          if (_this.$f7.data.from == 'wechat') {
            console.log('wechat to ready ');
            wx.ready(function () {
              console.log('wechat ready ');
              let _successPosition = function (res) {
                console.log('wechat position : ', res);
                let latitude_wgs84 = res.latitude ? res.latitude : 0;
                let longitude_wgs84 = res.longitude ? res.longitude : 0;

                let r = tacentToBaiduMap(longitude_wgs84, latitude_wgs84);
                _this.curLongitude = r.lng;
                _this.curLatitude = r.lat;
                resolve(r);
              };
              let _errorPosition = (err) => {
                reject(err);
              };
              let params = {
                success: _successPosition,
                error: _errorPosition,
              };
              WeChatUtils.getLocation(_this, params);
            });
          } else {
            dd.ready(function () {
              dd.device.geolocation.get({
                targetAccuracy: 10,
                coordinate: 1,
                withReGeocode: false,
                useCache: true, //默认是true，如果需要频繁获取地理位置，请设置false
                onSuccess: function (res) {
                  /* 高德坐标 result 结构
                   {
                   longitude : Number,
                   latitude : Number,
                   accuracy : Number,
                   address : String,
                   province : String,
                   city : String,
                   district : String,
                   road : String,
                   netType : String,
                   operatorType : String,
                   errorMessage : String,
                   errorCode : Number,
                   isWifiEnabled : Boolean,
                   isGpsEnabled : Boolean,
                   isFromMock : Boolean,
                   provider : wifi|lbs|gps,
                   isMobileEnabled : Boolean
                   }
                   */
                  let latitude_wgs84 = res.latitude ? res.latitude : 0;
                  let longitude_wgs84 = res.longitude ? res.longitude : 0;

                  let r = tacentToBaiduMap(longitude_wgs84, latitude_wgs84);
                  _this.curLongitude = r.lng;
                  _this.curLatitude = r.lat;
                  resolve(r);
                },
                onFail: function (err) {
                  reject(err);
                }
              });
            });
          }
        });
      },
      setMarkAtMap(longitude, latitude) {
        let _this = this;
        if (!_this.positionObj) {
          return false;
        }
        _this.positionObj.clearOverlays();
        if (latitude && longitude) {
          // console.log('----------')
          var new_point = new BMap.Point(longitude, latitude);
          var marker = new BMap.Marker(new_point);  // 创建标注

          // 以标记点设置签到范围圆形区域显示
          if (_this.range) {
            let circle = new BMap.Circle(new_point, _this.range, {
              fillColor: '#2CAFFF',
              strokeWeight: 1,
              fillOpacity: 0.3,
              strokeOpacity: 0.3,
            });
            _this.positionObj.addOverlay(circle);     // 将圆形区域添加至地图中
          }

          // 当前人所在位置
          if (_this.curLongitude && _this.curLatitude) {
            let curPoint = new BMap.Point(_this.curLongitude,
                _this.curLatitude);
            _this.setMyselfPositionIcon(curPoint);
          }

          _this.positionObj.addOverlay(marker);     // 将标注添加到地图中
          _this.positionObj.panTo(new_point);

        }
      },
    },
    created() {
      this.onCreated();
    },
    mounted() {
      this.onMounted();
    },
  }
</script>

<style scoped>
</style>